#include "IwSound.h"
#include "AudioSystem.h"

#define MAIN_AUDIO_RESOURCE_GROUP_FILE "audio/resource.group"
#define MAIN_AUDIO_RESOURCE_GROUP_NAME "audio"

void AudioSystem::Load()
{
	MusicInstance = NULL;
	AudioStorage storage;
	storage.Load( this );

	// Volume = iwsfixed(IW_FIXED( storage.GetVolume() ));

	IwGetResManager()->LoadGroup( MAIN_AUDIO_RESOURCE_GROUP_FILE );
	soundres_group = IwGetResManager()->GetGroupNamed( MAIN_AUDIO_RESOURCE_GROUP_NAME );
	
	//Init the background music and play it :D
	SoundSpec = (CIwSoundSpec*)soundres_group->GetResNamed("backgroundmusic", IW_SOUND_RESTYPE_SPEC);
	MusicInstance = SoundSpec->Play();
	MusicInstance->SetVol(Volume);
}

void AudioSystem::Unload()
{
	AudioStorage storage;
	storage.Save( this );

	// delete SoundInstance;  // delete it
}

void AudioSystem::Update(float dt)
{
}

void AudioSystem::Render()
{
}

void AudioSystem::Play(const char* ZeSoundName)
{
	SoundSpec = (CIwSoundSpec*)soundres_group->GetResNamed(ZeSoundName, IW_SOUND_RESTYPE_SPEC);
	SoundInstance = SoundSpec->Play();
	SoundInstance->SetVol(Volume);	
}

void AudioStorage::Serialise()
{
	IwSerialiseFloat( m_volume );
}

void AudioStorage::Save( AudioSystem *audio_system )
{
	m_volume = audio_system->GetVolume();
	
	// setup the default scores for all levels
    IwSerialiseOpen("settings.bin", false);
    
    Serialise();

    // close the file
    IwSerialiseClose();
}

void AudioStorage::Load( AudioSystem *audio_system )
{
	if( IwSerialiseExists( "settings.bin", false ) == false ) {
		audio_system->SetVolume( 1.0f );
	
        // and save it
        Save( audio_system );
    } else {
        IwSerialiseOpen("settings.bin", true);

        Serialise();

        // close the file
        IwSerialiseClose();
        
        audio_system->SetVolume( m_volume );
    }
}